import {Form, Input, Tree, Button, message, Checkbox, Row, Col  } from 'antd';
import React from 'react';
import * as Request from '../../Server/SystemManger';
import * as Utils from '../../common/utils';
import * as Const from '../../common/const';
import qs from 'qs';
require('./customer.css');

const FormItem = Form.Item;
const TreeNode = Tree.TreeNode;
const MENU_TYPE = 1;//权限类型,菜单

class RoleForms extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            selectedKeys: [],
            treeData: [],
            name: '',
            id: '',
            checkedId: [],
            checkedKeys: [],
            expandedKeys: [],
        };
    }

    componentDidMount() {
        Request.saveRoleGo().then(res => {
            if (res && Const.REQUEST_SUCCESS == res.code) {
                const treeMap = {};
                const treeData = Utils.getTreeDataForNesting(res.data.permissionList, treeMap);
                this.setState({treeData: treeData, expandedKeys: [treeData[0].key]});
                this.setChecked(treeMap,treeData);
            }
        });
    }

    componentWillUnmount() {
        this.setState = (state, callback) => {
            return;
        };
    }

    setChecked = (treeMap) => {
        if (this.props.id != null) {
            Request.getRoleById(this.props.id).then(res => {
                if (res && Const.REQUEST_SUCCESS == res.code) {
                    const checkedKeys = Utils.getTreeDataKeys(treeMap,res.data.permissionList);
                    let {checked,halfChecked} = checkedKeys;
                    checked = this.autoCheckedParent(this.state.treeData,[],checked);
                    this.setState({
                        checkedKeys: {checked:checked,halfChecked:this.getHalfChecked(checked,halfChecked)},
                        name: res.data.name,
                        id: res.data.id,
                        expandedKeys: res.data.permissionList.length ? Utils.getExpandKeys([...checked,...halfChecked]): this.state.expandedKeys,
                        checkedId: Utils.getPermissionIds(res.data.permissionList),
                    });
                }
            });
        }
    }


    handleSubmit = (e) => {
        e.preventDefault();
        const _this = this;
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                const permissionids = _this.state.checkedId;
                const params = {
                    name: values.name.replace(/\s*/g,""),
                    permissionids: permissionids
                };
                _this.state.id != Const.EMPTY_STR ? Object.assign(params, {id: _this.state.id}) : null;
                Request.editOrSaveRole(qs.stringify(params, {indices: false})).then(res => {
                    if (res && Const.REQUEST_SUCCESS == res.code) {
                        _this.props.cancel();
                        message.success(_this.state.id ? '编辑角色成功' : '新增角色成功', 1);
                    }
                })
            }
        });
    }

    onCheck = (checkedKeys, e) => {
        const node = e.node;
        let {checked, halfChecked} = checkedKeys;
        if (node.props.children) {
            if (e.checked && !node.props.halfChecked) {//全选
                checked = this.autoSelectAll(this.state.treeData, checked);
            } else if (!e.checked && !node.props.halfChecked) { // 只勾选父节点
                checked = checked.filter(x => x.indexOf(`${node.props.eventKey}-`) == -1 && x  !== node.props.eventKey );
                halfChecked = [...halfChecked,node.props.eventKey,...this.getHalfCheckedChildren(node.props.children)];
            } else if (e.checked && node.props.halfChecked) { //全不选
                checked = checked.filter(x => x.indexOf(`${node.props.eventKey}-`) == -1 && x  !== node.props.eventKey );
                halfChecked = halfChecked.filter(item => item !== node.props.eventKey && item.indexOf(`${node.props.eventKey}-`) == -1);
            }
        }
        checked = this.autoCheckedParent(this.state.treeData, [], checked);
        if(!e.checked){
            checked = checked.filter(x => node.props.eventKey.indexOf(`${x}-`) == -1);
        }
        halfChecked = this.getHalfChecked(checked,halfChecked);

        let checkedId = [];
        [...checked,...halfChecked].map(item => {
             let array = item.split('-');
             array = array.splice(1,array.length);
             checkedId = [...checkedId,...array];
         });
         checkedId = Utils.distinctArray(checkedId);
         checkedId.map(item => Number(item));
        this.setState({checkedKeys: {checked: checked, halfChecked: halfChecked},checkedId});
    }

    //勾选父节点自动勾选对应的子节点
    autoSelectAll = (treeData, checked = []) => {
        treeData.map(item => {
            if (checked.includes(item.key)) {
                item.children && this.pushKey(item.children, checked);
            } else {
                item.children && this.autoSelectAll(item.children, checked);
            }
        });
        return Utils.distinctArray(checked);
    }
    pushKey = (treeData, checked = []) => {
        treeData.map(item => {
            checked.push(item.key);
            item.children && this.pushKey(item.children, checked);
        });
    }
    autoCheckedParent = (treeData, parent, checked = []) => { //自动勾选父节点
        treeData.map(item => {
            if (item.children) {
                this.autoCheckedParent(item.children, item, checked);
            }
            if(parent.children){
                let flag = true;
                parent.children.map(temp => {
                    if (!checked.includes(temp.key)) {
                        flag = false;
                    }
                });
                flag && checked.push(parent.key);
            }
        });
        return  Utils.distinctArray(checked);
    }
    getHalfChecked = (checked,halfChecked = []) => {
        [...checked,...halfChecked].map(item => {
            let current = item;
            while (typeof current == 'string' && current.indexOf('-') !== -1) {
                current = current.substring(0, current.lastIndexOf('-'))
                if (!checked.includes(current)) {
                    !halfChecked.includes(current) && halfChecked.push(current);
                }
            }
        });
        halfChecked = halfChecked.filter(item => !checked.includes(item));
        return  Utils.distinctArray(halfChecked);
    }
    getHalfCheckedChildren = (data,halfChecked = []) =>{
        data.map(item => {
            const props = item.props;
            if(props.dataRef.type == MENU_TYPE){
                halfChecked.push(props.dataRef.key);
            }
            if(props.children){
                this.getHalfCheckedChildren(props.children,halfChecked);
            }
        })
        return halfChecked;
    }
    onExpand = (expandedKeys) => {
        this.setState({expandedKeys});
    }
    onSelect = (selectedKeys, info) => {
        this.setState({selectedKeys});
    }
    //校验角色名称是否合法
    validateRoleName = (rule, value, callback) => {
        if (value && value.length) {
            const params = {name: value};
            this.props.id && (params.id = this.props.id);
            Request.validatorRole(qs.stringify(params)).then(res => {
                if (res && Const.REQUEST_SUCCESS == res.code && !res.data) {
                    callback(Const.VALIDATOR_FAIL_TIP);
                } else {
                    callback();//注意:回调函数必须调用
                }
            });
        } else {
            callback();
        }
    }
    renderTreeNodes = (data) => {
        return data.map((item) => {
            if (item.children && item.children.length) {
                return (
                    <TreeNode title={item.title} key={item.key} dataRef={item}>
                        {this.renderTreeNodes(item.children)}
                    </TreeNode>
                );
            }
            delete item.children;
            return <TreeNode title={item.title} key={item.key} dataRef={item}/>;
        });
    }

    render() {
        const {getFieldDecorator} = this.props.form;

        const formItemLayout = {
            labelCol: {
                xs: {span: 24},
                sm: {span: 8},
            },
            wrapperCol: {
                xs: {span: 24},
                sm: {span: 10},
            },
        };

        return (
            <Form onSubmit={this.handleSubmit}>
                <FormItem>
                    {getFieldDecorator('id', {
                        initialValue: this.state.id,
                    })(
                        <Input type={'hidden'}/>
                    )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="角色名称"
                >
                    {getFieldDecorator('name', {
                        rules: [{
                            required: true, message: '请输入角色名称!',
                        }, {
                            validator: this.validateRoleName,
                        }],
                        initialValue: this.state.name,
                    })(
                        <Input disabled={this.props.disabled} maxLength={255}/>
                    )}
                </FormItem>
                <Row>
                    <Col {...{xs: 0, sm: 4, md: 6 }} ></Col> 
                    <Col {...{xs: 24, sm: 19, md: 16 }} style={{ marginTop: 10 }} className='check-box-margin'>
                        <Col {...{xs: 24, sm: 24, md: 10, lg: 7, xl: 6 }}>
                            <Checkbox checked={true} readOnly={true} className='check-box-text'>单击全选为编辑权限</Checkbox>  
                        </Col>
                        <Col {...{xs: 24, sm: 24, md: 12, lg: 10, xl: 8 }}>
                            <Checkbox checked={true} readOnly={true} className='check-box-text checkbox1'>双击为只读权限，仅能查看</Checkbox>  
                        </Col>
                    </Col>
                </Row>
                <FormItem
                    {...formItemLayout}
                    label="资源列表"
                >
                    {getFieldDecorator('permission')(
                        <Tree showLne checkable
                            checkedKeys={this.state.checkedKeys}
                            onCheck={this.onCheck}
                            onSelect={this.onSelect}
                            disabled={this.props.disabled}
                            onExpand={this.onExpand}
                            expandedKeys={this.state.expandedKeys}
                            checkStrictly={true}
                        >
                            {this.renderTreeNodes(this.state.treeData)}
                        </Tree>
                    )}
                    <style>{`
                        .ant-tree-checkbox-indeterminate .ant-tree-checkbox-inner:after{
                            content: ' ';
                            -webkit-transform: translate(-50%, -50%) scale(1);
                            -ms-transform: translate(-50%, -50%) scale(1);
                            transform: scale(1);
                            border: 1px solid white;
                            left: 2.42857143px;
                            top: 5.92857143px;
                            width: 9.14285714px;
                            height: 1.14285714px;
                            background-color: #1890ff;
                            position: absolute;
                            opacity: 1;
                        }
                        .ant-checkbox {
                            cursor: default
                        }
                        .ant-checkbox-input {
                            cursor: default
                        }
                        .checkbox1 .ant-checkbox-checked .ant-checkbox-inner:after {
                            -webkit-transform: rotate(90deg);
                            -ms-transform: rotate(90deg);
                            transform: rotate(90deg);
                            position: absolute;
                            display: table;
                            border: 2px solid #fff;
                            border-top: 0;
                            border-left: 0;
                            border-bottom: 0;
                            content: ' ';
                            -webkit-transition: all 0.2s cubic-bezier(0.12, 0.4, 0.29, 1.46) 0.1s;
                            -o-transition: all 0.2s cubic-bezier(0.12, 0.4, 0.29, 1.46) 0.1s;
                            transition: all 0.2s cubic-bezier(0.12, 0.4, 0.29, 1.46) 0.1s;
                            opacity: 1;
                        }

                    `}</style>
                </FormItem>
                {<FormItem style={{textAlign: 'center'}}>
                    {!(this.props.id && this.props.disabled) && <Button type="primary" htmlType="submit">保存</Button>}
                    <Button type="primary" onClick={this.props.cancel}>返回</Button>
                </FormItem>}
            </Form>
        );
    }
}

const WrappedRoleForms = Form.create()(RoleForms);

export default WrappedRoleForms;